<template>
  <div class="app-container">
    <el-card class="box-card" :bordered="false" shadow="never">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="审核状态">
            <el-select v-model="filterForm.auditStatus" placeholder="请选择审核状态" @change="handleFilterChange">
              <el-option label="全部" value="" />
              <el-option label="待审核" value="1" />
              <el-option label="审核成功" value="2" />
              <el-option label="审核拒绝" value="3" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <el-table v-loading="listLoading" :data="tableData.data" size="small" style="width: 100%">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="productName" label="商品名称" min-width="150" :show-overflow-tooltip="true" />

        <el-table-column prop="productImage" label="新商品详情图" width="120">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                v-for="(value, index) in getImageArray(scope.row.newDescription)"
                :key="index"
                :src="value"
                :preview-src-list="getImageArray(scope.row.newDescription)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productImage" label="旧商品详情图" width="120">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                v-for="(value, index) in getImageArray(scope.row.productImage)"
                :key="index"
                :src="value"
                :preview-src-list="getImageArray(scope.row.productImage)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="新轮播图" width="150">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                v-for="(value, index) in getSliderImageArray(scope.row.newSliderImage)"
                :key="index"
                :src="value"
                :preview-src-list="getSliderImageArray(scope.row.newSliderImage)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="旧轮播图" width="150">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                v-for="(value, index) in getSliderImageArray(scope.row.oldSliderImage)"
                :key="index"
                :src="value"
                :preview-src-list="getSliderImageArray(scope.row.oldSliderImage)"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="旧商品规格" width="150">
          <template slot-scope="scope">
            <span>长:{{ scope.row.oldLength }}mm</span><br />
            <span>宽:{{ scope.row.oldWide }}mm</span><br />
            <span>高:{{ scope.row.oldHigh }}mm</span><br /> </template
        ></el-table-column>
        <el-table-column label="新商品规格" width="150">
          <template slot-scope="scope">
            <span>长:{{ scope.row.newLength }}mm</span><br />
            <span>宽:{{ scope.row.newWide }}mm</span><br />
            <span>高:{{ scope.row.newHigh }}mm</span><br /> </template
        ></el-table-column>
        <el-table-column prop="productPrice" label="标准档价格" width="100" />

        <!-- <el-table-column prop="productDesc" label="商品简介" min-width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.intro }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="merchantName" label="已选工厂" width="150" />

        <el-table-column prop="allCrowdCost" label="众筹总金额" width="120" />
        <el-table-column prop="predictAllEarnings" label="净收益" width="120" />

        <el-table-column prop="allCrowdNum" label="众筹数量" width="100" />

        <el-table-column prop="createTime" label="众筹时间" width="80" />

        <el-table-column prop="drawDesignCost" label="打样费" width="80" />
        <el-table-column prop="packCost" label="包装费" width="80" />

        <el-table-column prop="dieSinkingCost" label="开模费" width="80" />

        <el-table-column prop="bigGoodsCost" label="工厂报价" width="100" /> -->

        <el-table-column prop="playerName" label="作者" width="100">
          <!-- 蓝色字显示 -->
          <template slot-scope="scope">
            <span
              style="color: blue; cursor: pointer"
              v-if="scope.row.playerName"
              @click="handleClickPlayer(scope.row.playerName)"
              >{{ scope.row.playerName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="playerPhone" label="作者手机号" width="100" />

        <el-table-column prop="createTime" label="申请时间" width="100" />

        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template slot-scope="scope">
            <!-- <span v-if="scope.row.auditStatus == 0">无需审核</span> -->
            <el-tag v-if="scope.row.auditStatus == 1" type="info">待审核</el-tag>
            <el-tag v-else-if="scope.row.auditStatus == 2" type="success">审核成功</el-tag>
            <el-tag v-else-if="scope.row.auditStatus == 3" type="danger">审核拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template slot-scope="scope">
            <div v-hasPermi="['productAudit:audit']" style="width: 120px">
              <div v-if="scope.row.auditStatus == 1" style="width: 120px; display: flex">
                <el-button type="text" size="small" @click="handleReject(scope.row)" style="color: blue"
                  >驳回</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="handleApprove(scope.row)"
                  style="color: blue; margin-left: 0px"
                  >通过</el-button
                >
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="block mt20">
        <el-pagination
          background
          :page-sizes="[10, 20, 50, 100]"
          :page-size="tableForm.limit"
          :current-page="tableForm.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 驳回弹窗 -->
    <el-dialog title="驳回原因" :visible.sync="dialogVisible" width="400px">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="驳回原因" prop="reason">
          <el-input type="textarea" v-model="form.reason" placeholder="请输入驳回原因" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReject">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editAuditListApi, editAuditApi } from '@/api/product';
import { checkPermi } from '@/utils/permission';

export default {
  name: 'editAudit',
  components: {},
  data() {
    return {
      activeTab: '1', // 当前激活的标签页
      listLoading: false, // 表格加载状态
      tableData: {
        data: [
          {
            id: 1,
            productImage: 'https://img.alicdn.com/tfs/TB1vT0T8AL0gK0jSZFxXXa9kXXa-400-400.jpg',
            productName: '口袋照',
            standardPrice: 150.0,
            productDesc: '这一个熊的故事...',
            crowdfundingAmount: 200000.0,
            crowdfundingQuantity: 5000,
            crowdfundingTime: 30,
            proofingFee: 100.0,
            moldFee: 0.0,
            factoryPrice: 85.0,
            author: '李氏哪个',
          },
        ],
        total: 3,
      },
      tableForm: {
        page: 1,
        limit: 10,
      },
      // 筛选表单
      filterForm: {
        auditStatus: '', // 审核状态筛选
      },
      // searchForm已删除
      dialogVisible: false, // 驳回弹窗显示状态
      currentRow: null, // 当前操作的行数据
      form: {
        reason: '',
      },
      rules: {
        reason: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getSliderImageArray(sliderImageStr) {
      if (!sliderImageStr) return [];

      try {
        // 尝试解析JSON字符串
        let images = JSON.parse(sliderImageStr);

        // 确保是数组
        if (Array.isArray(images)) {
          // 清理每个图片URL中的特殊字符
          return images
            .map((img) => {
              // 处理对象格式 {"url": "图片地址"}
              if (typeof img === 'object' && img !== null && img.url) {
                return img.url.replace(/[`]/g, '').trim();
              }
              // 处理字符串格式
              if (typeof img === 'string') {
                return img.replace(/[`]/g, '').trim();
              }
              return '';
            })
            .filter((img) => img && img.startsWith('http'));
        }
      } catch (error) {
        // JSON解析失败，可能是单个URL格式
        if (typeof sliderImageStr === 'string') {
          // 直接清理单个URL中的特殊字符
          const cleanedUrl = sliderImageStr.replace(/[`]/g, '').trim();
          // 检查是否是有效的URL格式
          if (cleanedUrl && cleanedUrl.startsWith('http')) {
            return [cleanedUrl];
          }
        }
        console.error('解析轮播图数据失败:', error);
      }
      return [];
    },
    // 将逗号分隔的图片字符串转换为数组
    getImageArray(imageStr) {
      if (!imageStr) return [];
      return imageStr.split(',').filter((img) => img.trim());
    }, // 标签页切换
    handleTabClick() {
      this.tableForm.page = 1;
      this.getList();
    },

    // 获取列表数据
    getList() {
      this.listLoading = true;
      const params = {
        ...this.tableForm,
        auditStatus: this.activeTab,
        auditStatus: this.filterForm.auditStatus || undefined, // 添加审核状态筛选条件
      };
      // 模拟API调用，实际项目中请使用真实的API
      editAuditListApi(params)
        .then((res) => {
          this.tableData.data = res.list || [];
          this.tableData.total = res.total || 0;
        })
        .catch((err) => {
          console.error('获取众筹审核列表失败:', err);
          // 如果API调用失败，使用模拟数据
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 筛选条件变化处理
    handleFilterChange() {
      this.tableForm.page = 1; // 筛选条件变化时重置到第一页
      this.getList();
    },

    // search()方法已删除

    // reset()方法已删除

    // 分页改变
    pageChange(page) {
      this.tableForm.page = page;
      this.getList();
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.tableForm.limit = val;
      this.getList();
    },

    // 处理驳回
    handleReject(row) {
      this.currentRow = row;
      this.form.reason = '';
      this.dialogVisible = true;
    },

    // 提交驳回
    submitReject() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 使用editAuditApi进行驳回操作
          const params = {
            id: this.currentRow.id,
            auditStatus: 3, // 3-审核拒绝
            auditRemark: this.form.reason,
          };

          this.listLoading = true;
          console.log('驳回参数:', params);
          editAuditApi(params)
            .then(() => {
              this.$message.success('驳回成功');
              this.dialogVisible = false;
              this.getList();
            })
            .catch((err) => {
              console.error('驳回操作失败:', err);
              this.$message.error('驳回失败，请重试');
            })
            .finally(() => {
              this.listLoading = false;
            });
        }
      });
    },
    // 去选手列表
    handleClickPlayer(name) {
      this.$router.push({
        path: '/marketing/community/player',
        query: {
          playerName: name,
        },
      });
    },

    // 处理通过
    // 处理通过
    handleApprove(row) {
      this.$confirm('确定要通过该众筹产品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 使用editAuditApi进行通过操作
          const params = {
            id: row.id,
            auditStatus: 2, // 2-审核成功
            auditRemark: '审核通过',
          };

          console.log('参数:', params);
          // return;
          this.listLoading = true;
          editAuditApi(params)
            .then(() => {
              this.$message.success('通过成功');
              this.getList();
            })
            .catch((err) => {
              console.error('通过操作失败:', err);
              this.$message.error('通过失败，请重试');
            })
            .finally(() => {
              this.listLoading = false;
            });
        })
        .catch(() => {});
    },

    // 检查权限
    checkPermi,
  },
};
</script>

<style scoped>
.box-card {
  padding: 20px;
}

.demo-image__preview {
  width: 100%;
  height: 60px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.demo-image__preview img {
  max-width: 100%;
  max-height: 100%;
}

.list-tabs {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

.row_title {
  flex: 1;
  font-size: 14px;
}

.line2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.filter-container {
  padding: 10px 0;
}
</style>
